package com.module_video.activity;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.lib.app.ARouterPathUtils;
import com.lib.app.CodeUtil;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.json_deal.lib_mgson.MGson;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.views.dialog.normal.CoachAIStudyDialog;
import com.lib.fastkit.views.recyclerview.zhanghongyang.base.ViewHolder;
import com.lib.http.call_back.HttpDialogCallBack;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.ui.activity.BaseAppActivity;
import com.lib.ui.adapter.BaseAdapter;
import com.lib.utls.glide.GlideConfig;
import com.lib.view.navigationbar.NomalNavigationBar;
import com.lib.view.player.MyJzvdStd;
import com.module_video.R;
import com.module_video.R2;
import com.module_video.bean.ClassDeatilBean;
import com.module_video.bean.MainInfoBean_1;
import com.module_video.bean.OperateBean;
import com.module_video.bean.StudentCollectedVideoBean;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jzvd.JZUtils;
import cn.jzvd.Jzvd;

/**
 * Created by Administrator on 2020/7/17 0017.
 */

@Route(path = ARouterPathUtils.Tablet_Video_RecordDetailActivity)
public class RecordDetailActivity extends BaseAppActivity {

    @BindView(R2.id.jz_detailplay)
    MyJzvdStd jzDetailplay;

    @BindView(R2.id.tv_title)
    TextView tvTitle;
    @BindView(R2.id.tv_grade)
    TextView tvGrade;
    @BindView(R2.id.tv_time)
    TextView tvTime;
    @BindView(R2.id.tv_collect)
    TextView tvCollect;
    @BindView(R2.id.tv_classdescribe)
    TextView tvClassdescribe;

    @BindView(R2.id.rv_list)
    RecyclerView rvList;

    //传递过来的数据，视频的id以及视频信息
    @Autowired(name = "recordId")
    int recordId;
    @Autowired(name = "recordJson")
    String recordJson;
    @Autowired(name = "showType")
    String showType;

    ClassListAdapter classListAdapter;

    //装载课程列表中的文本
    private List<TextView> tvColotList = new ArrayList<>();

    private int startPlayingPosition;

    //当前播放视频的Id
    private int videoId = -1;
    private String playUrl = "";

    //当前播放视频的是否收藏   0-未收藏，1-已收藏
    private int isCollect = -1;

    List<ClassDeatilBean.ObjBean> classList = new ArrayList<>();

    private boolean isPlayResume = false;

    @Override
    protected void onCreateView() {

        recordId = getIntent().getIntExtra("recordId", -1);
        recordJson = getIntent().getStringExtra("recordJson");
        showType = getIntent().getStringExtra("showType");

        initView();

        //初始化右边视频列表
        initClassData();

        //初始化首页点击录播课的详细信息
        initRecordClassData();

        tvCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //发送关注状态到服务器
                sendVideoCareStateToService();
            }
        });
    }

    //videoCollect的值来判断收藏还是取消
    private void sendVideoCareStateToService() {

        HttpUtils.with(this)
                .addParam("requestType", "ADD_OR_REMOVE_FAVORITES")
                .addParam("recorded_lesson_id", videoId)
                .addParam("lok_or_jfzl", 0)
                .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                .execute(new HttpDialogCallBack<OperateBean>() {
                    @Override
                    public void onSuccess(OperateBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            if (0 == result.getObj().getIs_favorites()) {

                                showToast("取消收藏成功！");
                                tvCollect.setText("收藏");

                            } else if (1 == result.getObj().getIs_favorites()) {

                                showToast("恭喜您，收藏成功，可以在个人中心查看哦！");
                                tvCollect.setText("已收藏");
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }


    private void initRecordClassData() {

        if (StringUtil.isNotEmpty(recordJson, true)) {

            if ("MainRecord".equals(showType)) {

                MainInfoBean_1.ObjBean.RecordingClassBean finalClassBean =
                        MGson.newGson().fromJson(recordJson, MainInfoBean_1.ObjBean.RecordingClassBean.class);

                //初始化标题title
                initTitle(finalClassBean.getVideo_title());

                videoId = finalClassBean.getId();
                isCollect = finalClassBean.getIs_favorites();

                //初始化视频播放
                initPlayVideo(finalClassBean.getVideo_url(), finalClassBean.getVideo_title(), finalClassBean.getCover());

                //初始化视频信息及收藏状态
                initVideoInfo(finalClassBean.getVideo_title(), finalClassBean.getCreation_date(),
                        finalClassBean.getGrade_name(), finalClassBean.getSubject_name());

                //显示课程内容描述
                tvClassdescribe.setText(finalClassBean.getVideo_title());

            } else if ("UserCollect".equals(showType)) {

                StudentCollectedVideoBean.ObjBean.RowsBean collectVideoBean =
                        MGson.newGson().fromJson(recordJson, StudentCollectedVideoBean.ObjBean.RowsBean.class);

                //初始化标题title
                initTitle(collectVideoBean.getVideo_title());

                videoId = collectVideoBean.getId();
                isCollect = collectVideoBean.getIs_favorites();

                //初始化视频播放
                initPlayVideo(collectVideoBean.getVideo_url(), collectVideoBean.getVideo_title(), collectVideoBean.getVideo_cover());

                //初始化视频信息及收藏状态
                initVideoInfo(collectVideoBean.getVideo_title(), collectVideoBean.getCreation_date(),
                        collectVideoBean.getGrade_name(), collectVideoBean.getSubject_name());

                //显示课程内容描述
                tvClassdescribe.setText(collectVideoBean.getVideo_title());
            }


        }

    }


    private void initTitle(String title) {

        NomalNavigationBar navigationBar = new NomalNavigationBar.Builder(this)
                .setTitle(title)
                .setRightClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).builder();
        navigationBar.getView(R.id.right_icon).setVisibility(View.GONE);

    }

    //初始化视频信息及收藏状态
    public void initVideoInfo(String title, String createTime, String grade, String subject) {

        if (StringUtil.isNotEmpty(title, true)) {

            tvTitle.setText(title);
        }

        if (StringUtil.isNotEmpty(createTime, true)) {

            tvTime.setText(createTime);
        }

        if (StringUtil.isNotEmpty(grade, true) &&
                StringUtil.isNotEmpty(subject, true)) {

            tvGrade.setText(grade + " · " + subject);
        }

        //是否收藏，0-未收藏，1-已收藏
        if (isCollect > -1) {

            if (0 == isCollect) {
                tvCollect.setText("收藏");
            } else if (1 == isCollect) {
                tvCollect.setText("已收藏");
            }
        }

    }

    private void initView() {

        //设置视频可以保存进度
        Jzvd.SAVE_PROGRESS = true;

        //实例化数据库保存示例
        classListAdapter = new ClassListAdapter(this, classList);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rvList.setLayoutManager(manager);
        rvList.setAdapter(classListAdapter);

    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onResume() {

        /**
         * 设置为横屏
         */
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        super.onResume();
        if (isPlayResume) {
            jzDetailplay.goOnPlayOnResume();

            isPlayResume = false;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (jzDetailplay != null) {
            jzDetailplay.releaseAllVideos();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (jzDetailplay != null) {
            jzDetailplay.releaseAllVideos();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_recorddetail;
    }


    private void initClassData() {

        LogUtil.e("获取到视频id的值为：" + recordId);

        if (recordId > -1) {

            HttpUtils.with(this)
                    .addParam("requestType", "TABLET_RECORDING_CLASS_DETAILS")
                    .addParam("id", recordId)
                    .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                    .execute(new HttpNormalCallBack<ClassDeatilBean>() {
                        @Override
                        public void onSuccess(ClassDeatilBean result) {

                            if (CodeUtil.CODE_200 == result.getCode()) {

                                initClassList(result);
                            } else {

                                showToast(result.getMsg());
                            }
                        }

                        @Override
                        public void onError(String e) {
                        }
                    });
        }
    }

    private void initClassList(ClassDeatilBean result) {

        classList.clear();
        classList.addAll(result.getObj());
        classListAdapter.updateData(classList);
        classListAdapter.notifyDataSetChanged();

    }

    private void initPlayVideo(final String playVideoUrl, String videoTitle, String imgUrl) {

        LogUtil.e("当前要播放视频的播放地址为：" + playVideoUrl);

        if (!"".equals(playVideoUrl) && jzDetailplay != null && !"".equals(videoTitle)) {
            jzDetailplay.setUp(playVideoUrl, videoTitle);
            jzDetailplay.setVideoStateListener(stateListener);
            Glide.with(getApplicationContext()).load(imgUrl).into(jzDetailplay.thumbImageView);
        }

        if (0 != JZUtils.getSavedProgress(this, playVideoUrl)) {

            LogUtil.e("进度记录的的值为：" + JZUtils.getSavedProgress(this, playVideoUrl));

            CoachAIStudyDialog.getInstance()
                    .setTitle("温馨提示")
                    .setContent("您观看过本视频，请确定是否继续播放？")
                    .setSureListener(new CoachAIStudyDialog.SurelListener() {
                        @Override
                        public void onSure() {

                            jzDetailplay.seekToInAdvance = JZUtils.getSavedProgress(RecordDetailActivity.this, playVideoUrl);//跳转到指定的播放进度
                            jzDetailplay.startButton.performClick();//响应点击事件
                        }
                    })
                    .setCancelListener(new CoachAIStudyDialog.CancelListener() {
                        @Override
                        public void onCancel() {

                            jzDetailplay.seekToInAdvance = 0;//将视频从源头开始播放
                            jzDetailplay.startButton.performClick();//响应点击事件
                        }
                    }).show(getSupportFragmentManager());


        } else {

            LogUtil.e("当前视频无保存进度");

            if (jzDetailplay != null) {
                jzDetailplay.startVideo();
            }

        }

    }


    MyJzvdStd.VideoStateListener stateListener = new MyJzvdStd.VideoStateListener() {
        @Override
        public void videoPlaying() {

        }

        @Override
        public void videoBlackClick() {

            LogUtil.e("在播放视频时我被点击了");
        }

        @Override
        public void videoComplete() {

            if (jzDetailplay != null) {
                JZUtils.clearSavedProgress(RecordDetailActivity.this, playUrl);
            }

        }

        /**
         * 视频退出了，需要进行的操作
         *
         * 1.获取当前视频播放的进度
         * 2.根据videoId保存到实例类中，将该进度保存起来
         * 3.
         *
         */
        @Override
        public void videoReturnAndRecord() {

            if (jzDetailplay != null) {
                LogUtil.e("退出或切换时，当前进度值为：" + jzDetailplay.getCurrentPositionWhenPlaying() + "");

                JZUtils.saveProgress(RecordDetailActivity.this, playUrl, jzDetailplay.getCurrentPositionWhenPlaying());
            } else {
                LogUtil.e("退出或切换时，jzDetailplay为空");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    class ClassListAdapter extends BaseAdapter<ClassDeatilBean.ObjBean> {

        public ClassListAdapter(Context context, List<ClassDeatilBean.ObjBean> mData) {
            super(context, mData);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_recorddetail_list;
        }

        @Override
        protected void toBindViewHolder(final ViewHolder holder, final int position, final List<ClassDeatilBean.ObjBean> mData) {

            //获取并设置背景图片
            ImageView backImg = holder.getView(R.id.iv_backimg);

            Glide.with(RecordDetailActivity.this)
                    .load(mData.get(position).getVideo_cover())
                    .apply(GlideConfig.getRoundOptions(20))
                    .into(backImg);

            final TextView tvTitle = holder.getView(R.id.tv_title);
            tvColotList.add(tvTitle);
            tvTitle.setText(mData.get(position).getVideo_title());

            if (startPlayingPosition == position) {
                tvTitle.setTextColor(getResources().getColor(R.color.c5));
            }

            //开始播放和播放中文本
//            final ImageView ivStartPlaying = holder.getView(R2.id.iv_playimg);
//            final TextView tvPlaying = holder.getView(R2.id.tv_playing);

            holder.getView(R.id.lin_item).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    initTitleColor();

                    //判断点击的位置与播放的位置是否相同
                    if (startPlayingPosition == position) {

                        showToast("当前视频正在播放中！");

                    } else {
                        startPlayingPosition = position;
                        //保存上一个视频播放的进度
                        JZUtils.saveProgress(RecordDetailActivity.this, playUrl, jzDetailplay.getCurrentPositionWhenPlaying());

                        videoId = mData.get(position).getId();
                        isCollect = mData.get(position).getIs_favorites();

                        //初始化视频信息及收藏状态
                        initVideoInfo(mData.get(position).getVideo_title(),
                                mData.get(position).getCreation_date(),
                                mData.get(position).getGrade_name(),
                                mData.get(position).getSubject_name());

                        //将点击位置的视频添加到播放中
                        initPlayVideo(mData.get(position).getVideo_url(),
                                mData.get(position).getVideo_title(),
                                mData.get(position).getVideo_cover());
                    }
                    tvTitle.setTextColor(getResources().getColor(R.color.c5));
                }
            });
        }

    }

    private void getItemSize(ViewHolder holder) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) ((getResources().getDisplayMetrics().widthPixels
                - 104) / 3f), ViewGroup.LayoutParams.MATCH_PARENT);
        holder.getView(R.id.lin_item).setLayoutParams(params);
    }

    private void initTitleColor() {

        for (TextView textView : tvColotList) {
            textView.setTextColor(getResources().getColor(R.color.base_title));
        }

    }

}
